ITEM = {}

local ITEM_MAX_SLOT = 100

-- 创建物品
function ITEM.create_item(id, num)
    local item = item_t:new()
    item.id = id
    item.num = num
    item.timestamp = os.time()
    return item
end

local function find_vacancy(user)
    local items = user.items
    local pos = 0
    for i=1,ITEM_MAX_SLOT do
        if not items[i] then
            pos = i
            break
        end
    end
    return pos
end

function ITEM.find_item(user, id)
    local pos = 0
    local item = nil
    for index,myitem in pairs(user.items) do
        if myitem.id == id then
            pos = index
            item = myitem
            break
        end
    end

    return pos, item
end

-- 加入物品，该接口总是创建一个新物品
function ITEM.add_item(user, id, num)
    local item = ITEM.create_item(id,num)
    local items = user.items
    local pos = find_vacancy(user)
    if pos == 0 then
        tell_me("物品背包已满")
        return 0,nil
    end
    user:set_items(pos,item)
    return pos, item
end

-- 叠加物品，当没有改物品时候创建
function stack_item(user, id, num)
    local pos = 0
    local item = nil
    pos, item = ITEM.find_item(user,id)
    if not item then
        pos,item = Item.add_item(user,id,num)
        if not item then
            return 0,nil
        end
    end
    return pos, item
end

-- 删除物品
function ITEM.delete_item(user, args)
    local id = args.id
    local index = args.index
    local num = args.num

    local pos = 0
    local item = nil
    if id then
        pos, item = ITEM.find_item(user,id)
    else
        pos = index
        item = user:get_items(pos)
    end

    if not item then
        tell_me("找不到该物品")
        return 0,nil
    end

    local left = item.num - num
    if left < 0 then
        tell_me("没有足够的物品")
        return 0,nil
    elseif left == 0 then
        user:set_items(pos,nil)
    end
    item.num = left
    user:set_items(pos,item)
    return pos,item
end

function ITEM.func(user,data)

end

return ITEM
